<?php

namespace App\Providers;

use App\Models\PersonalAccessToken;
use Illuminate\Http\Resources\Json\JsonResource;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\ServiceProvider;
use Laravel\Sanctum\Sanctum;


class AppServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        /**
         * 特定包放入 dont-discover, 禁止自动加载, 优化性能
         * 根据不同环境/条件手动注册
         * */
        if ($this->app->isLocal()) {
            $this->app->register(\Barryvdh\LaravelIdeHelper\IdeHelperServiceProvider::class);
        }

        // 控制台
        if ($this->app->runningInConsole()) {
            $this->app->register(\Laravel\Tinker\TinkerServiceProvider::class);
            $this->app->register(\Orangehill\Iseed\IseedServiceProvider::class);
            // $this->app->register(\Facade\Ignition\IgnitionServiceProvider::class);
        }

        // 非API接口
        if (!request()->is('api/*')) {
            $this->app->register(\Laravel\Horizon\HorizonServiceProvider::class);
            $this->app->register(\App\Providers\HorizonServiceProvider::class);
            $this->app->register(\Maatwebsite\Excel\ExcelServiceProvider::class);
            $this->app->register(\Madnest\Madzipper\MadzipperServiceProvider::class);
            // $this->app->register(\App\Providers\ModelServiceProvider::class);
        }
    }

    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        // 生命周期检查
        if (request()->is('admin/*') && $adminLifeTime = config('admin.left_time')) {
            Sanctum::authenticateAccessTokensUsing(function(\App\Models\PersonalAccessToken $accessToken, $isValid) use ($adminLifeTime) {
                if ($accessToken->last_used_at && $accessToken->last_used_at->lt(now()->subSeconds($adminLifeTime))) return false;
                return true;
            });
        }

        // 禁用顶层资源的包裹
        JsonResource::withoutWrapping();

        // 自定义版本号验证规则
        Validator::extend('version', function ($attribute, $value, $parameters, $validator) {
            return preg_match('/^\d[\d.]+\d$/', $value);
        });

        // zh_mobile 不能正确识别 16 19号段, 且无法覆盖, 这里重写一个
        Validator::extend('cn_mobile', function ($attribute, $value) {
            return preg_match('/^(\+?0?86\-?)?(1[3456789]{1}\d{9})$/', $value);
        });

        // 使用自定义 PersonalAccessToken
        Sanctum::usePersonalAccessTokenModel(PersonalAccessToken::class);

        // 日志分离
        if (request()->is('api/*')) {
            Log::setDefaultDriver('daily');
        } elseif (request()->is('admin*')) {
            Log::setDefaultDriver('admin');
        } else {
            Log::setDefaultDriver('console');
        }
    }
}
